<?php

namespace Cblood\Route\Http;

class HttpRequest extends Http
{

    protected $service;

    public function __construct(HttpServer $service)
    {
        $this->service = $service;
    }

    public function input($name, $default = null)
    {
        return isset($_REQUEST[$name]) ? $_REQUEST[$name] : $default;
    }

    public function get($name, $default = null)
    {
        return isset($_GET[$name]) ? $_GET[$name] : $default;
    }

    public function post($name, $default = null)
    {
        return isset($_POST[$name]) ? $_POST[$name] : $default;
    }

    public function isGet()
    {
        return $this->service->get('REQUEST_METHOD') === 'GET';
    }

    public function isPost()
    {
        return $this->service->get('REQUEST_METHOD') === 'POST';
    }

    public function isAjax()
    {
        return $this->service->has('HTTP_X_REQUESTED_WITH') && strtolower($this->service->get('HTTP_X_REQUESTED_WITH')) == 'xmlhttprequest';
    }

    public function method()
    {
        return $this->service->get('REQUEST_METHOD');
    }

    public function host()
    {
        return $this->service->get('HTTP_HOST');
    }

    public function uri()
    {
        return $this->service->get('REQUEST_URI');
    }

    public function url()
    {
        $httpType = (($this->service->has('HTTPS') && $this->service->get('HTTPS') == 'on')
            || ($this->service->has('HTTP_X_FORWARDED_PROTO') && $this->service->get('HTTP_X_FORWARDED_PROTO') == 'https'))
            ? 'https://' : 'http://';

        return $httpType . $this->host() . $this->uri();
    }

    //基本路径不带参数的
    public function baseUri()
    {
        $uri = $this->uri();
        $number = strpos($uri, '?');
        if ($number) {
            $uri = substr($uri, 0, $number);
        }
        return $uri;
    }

    public function port()
    {
        return $this->service->get('SERVER_PORT');
    }

    public function file($name = null)
    {
        return $name ? $_FILES[$name] : $_FILES;
    }
}